/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.order;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.core.util.PrintUtils;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.orderdetail.OrderdetailService;
import shop.services.front.orderdetail.bean.Orderdetail;
import shop.services.front.record.RecordService;
import shop.services.front.record.bean.Record;
import shop.services.front.spec.SpecService;
import shop.services.front.spec.bean.Spec;
import shop.services.front.store.StoreService;
import shop.services.front.store.bean.Store;
import shop.services.front.voucherhave.VoucherhaveService;
import shop.services.front.voucherhave.bean.Voucherhave;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称：OrderController
 * @创建人：Wzl
 * @创建时间：2017-09-20 下午15:48:44
 * @版本号：1.0
 * @描述：订单
 */
@Controller
@RequestMapping("/front/order/")
public class OrderController extends FrontBaseController<Order> {
    private final static String RECORT_TYANSTYPE_CASH = "1";
    private final static String RECORT_TYANSTYPE_SUB_INORDER = "2";
    private final static String RECORT_TYANSTYPE_SUB_OUTORDER = "3";
    private final static String RECORT_TYANSTYPE_INCOME_INORDER = "4";
    private final static String RECORT_TYANSTYPE_INCOME_OUTORDER = "5";
    private final static String RECORT_TYANSTYPE_BALANCE_INORDER = "6";
    private final static String RECORT_TYANSTYPE_BALANCE_OUTORDER = "7";
    private final static String RECORT_TYANSTYPE_RECHARGE = "8";
    private final static String ORDER_TYPE_INSTORE = "in";
    private final static String ORDER_TYPE_OUTSTORE = "out";
    private final static String USER_ROLE_MANAGE_ADMIN = "1";
    private final static String USER_ROLE_FRONT_PARTNER = "2";
    private final static String USER_ROLE_FRONT_MEMBER = "3";
    private final static String USER_ROLE_FRONT_COMMON = "4";
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailService orderdetailService;
    @Resource
    private StoreService storeService;
    @Resource
    private SpecService specService;
    @Resource
    private UserService userService;
    @Resource
    private VoucherhaveService voucherhaveService;
    @Resource
    private RecordService recordService;

    @Override
    public Services<Order> getService() {
        return orderService;
    }


    /**
     * 跳转到订单列表页面
     *
     * @return
     */
    @RequestMapping("toOrderList")
    public String toOrderList() {
        return "/front/order/orderList";
    }

    /**
     * 跳转到订单详情页面（个人中心入口）
     *
     * @return
     */
    @RequestMapping("toOrderDetail")
    public String toOrderDetail() {
        return "/front/order/orderDetail";
    }

    /**
     * 跳转到订单详情页面（购物车入口）
     *
     * @return
     */
    @RequestMapping("toCartOrderDetail")
    public String toCartOrderDetail() {
        return "/front/order/cartOrderDetail";
    }

    /**
     * 跳转到用户礼卷列表页面
     *
     * @return
     */
    @RequestMapping("toVoucherList")
    public String toVoucherList() {
        return "/front/order/selectCard";
    }

    /**
     * 跳转到活动报名页面
     *
     * @return
     */
    @RequestMapping("toJoinActivity")
    public String toJoinActivity() {
        return "/front/order/joinActivity";
    }

    /**
     * 跳转到充值页面
     *
     * @return
     */
    @RequestMapping("toRecharge")
    public String toRecharge() {
        return "/front/order/accountMoney";
    }

    /**
     * 跳转到领取充值优惠礼卷页面
     *
     * @return
     */
    @RequestMapping("toGetCashVoucher")
    public ModelAndView toGetCashVoucher(HttpServletRequest request) {
        logger.debug("领取礼卷页面跳转: " + request.getRequestURI() + "?" + request.getQueryString());
        User user = (User) request.getSession().getAttribute("userInfo");
        if (!StringUtils.isBlank(request.getQueryString())) {
            String[] IDs = request.getQueryString().split("_");
            if (IDs.length == 2 && "0".equals(user.getPid())) {
                user.setPid(IDs[1]);
                user.setRid(USER_ROLE_FRONT_MEMBER);
                userService.update(user);
                request.getSession().setAttribute("userInfo", user);
                //会员加入模板消息通知
                User supUser = new User();
                supUser.setId(IDs[1]);
                supUser = userService.selectOne(supUser);
                Map<String, String> msgParam = new HashMap<>();
                msgParam.put("first", "尊敬的股东，您有新的会员加入！");
                msgParam.put("keyword1", user.getNickname());
                msgParam.put("keyword2", user.getPhone());
                msgParam.put("keyword3", user.getId());
                msgParam.put("remark", "点击查看详情");
                WxMsgUtil.sendMemberJoinMsg(msgParam, systemManager, supUser.getOpenID());
            }
        }
        ModelAndView modelAndView = new ModelAndView("/front/order/getCashVoucher");
        return modelAndView;
    }

    /**
     * 查询订单列表
     *
     * @param order
     * @return orderList
     */
    @RequestMapping(value = "selectOrderList", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderList(Order order) {
        JSONResult jsonResult = new JSONResult();
        logger.debug("用户ID：" + order.getUserID());
        List<Order> orderList = orderService.selectList(order);//查询用户订单列表
        for (int i = 0; i < orderList.size(); i++) {
            Order orderInfo = orderList.get(i);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(orderInfo.getId());
            orderList.get(i).setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));//添加订单详情
            Store store = new Store();
            store.setId(orderList.get(i).getStoreID());
            store = storeService.selectOne(store);
            orderList.get(i).setSellerName(store.getName());
        }
        jsonResult.setData(orderList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询订单详情（个人中心入口）
     *
     * @return
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderDetail(Orderdetail orderdetail) {
        Orderdetail orderdetailInfo = new Orderdetail();
        orderdetailInfo.setOrderID(orderdetail.getOrderID());
        List<Orderdetail> rsList = orderdetailService.selectOrderDetailList(orderdetailInfo);
        return new JSONResult(rsList, true);
    }

    /**
     * 查询用户订单地址
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "selectOrderAddress", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderAddress(Order order) {
        order = orderService.selectOne(order);
        jsonResult = new JSONResult();
        jsonResult.setData(order);
        return jsonResult;
    }

    /**
     * 继续下单
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "addOrderDetail", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult addOrderDetail(Order order) {
        String[] productIDs = order.getProductIDs().split(",");
        String[] specIDs = order.getSpecIDs().split(";");
        String[] productAmount = order.getProductAmount().split(",");
        for (int i = 0; i < productIDs.length; i++) {
            //获取规格信息
            Spec spec = new Spec();
            spec.setProductID(productIDs[i]);
            spec.setCombination(specIDs[i]);
            spec = specService.selectOne(spec);
            //创建订单详情项
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(order.getId());
            orderdetail.setProductID(productIDs[i]);
            orderdetail.setPrice(spec.getPrice());
            orderdetail.setNumber(Integer.valueOf(productAmount[i]));
            orderdetail.setSpecInfo(spec.getCombination());
            //计算订单详情项价格
            BigDecimal productNumber = new BigDecimal(productAmount[i]);
            productNumber.setScale(2, BigDecimal.ROUND_HALF_UP);//四舍五入保留两位小数
            BigDecimal total = spec.getPrice().multiply(productNumber);
            orderdetail.setDtotal(total);
            Orderdetail orderdetailInfo = orderdetailService.selectOne(orderdetail);
            if (orderdetailInfo == null) {
                orderdetailService.insert(orderdetail);//插入订单详情
            } else {
                orderdetailInfo.setPrice(orderdetailInfo.getPrice().add(spec.getPrice()));
                orderdetailInfo.setNumber(orderdetailInfo.getNumber() + Integer.valueOf(productAmount[i]));
                orderdetailInfo.setDtotal(orderdetailInfo.getDtotal().add(total));
                orderdetailService.update(orderdetailInfo);//更新订单详情
            }
        }
        jsonResult = new JSONResult();
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 余额抵扣
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "deductionOrder", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deductionOrder(HttpSession session, Order order) {
        User buyer = (User) session.getAttribute("userInfo");
        //插入订单
        int orderID = orderService.insert(order);
        order = orderService.selectOne(order);
        //更新买家个人数据
        buyer.setIncome(buyer.getIncome().subtract(order.getIncome()));
        buyer.setBalance(buyer.getBalance().subtract(order.getBalance()));
        BigDecimal score = buyer.getScore().add(order.getOtotal());
        buyer.setScore(score);
        userService.update(buyer);
        //更新买家礼卷数量
        if (!"0".equals(order.getVoucherID())) {
            Voucherhave voucherhave = new Voucherhave();
            voucherhave.setUserID(buyer.getId());
            voucherhave.setVoucherID(order.getVoucherID());
            voucherhave = voucherhaveService.selectOne(voucherhave);
            voucherhave.setAmount(voucherhave.getAmount() - 1);
            voucherhaveService.update(voucherhave);
            if (voucherhave.getAmount() == 0) {
                voucherhaveService.delete(voucherhave);
            }
        }
        //买家交易记录
        Record record = new Record();
        record.setUserID(buyer.getId());
        record.setTransID(order.getId());
        if (ORDER_TYPE_INSTORE.equals(order.getType()) && order.getIncome().compareTo(new BigDecimal(0)) != 0) {
            record.setTransType(RECORT_TYANSTYPE_INCOME_INORDER);
            record.setMoney(order.getIncome());
            recordService.insert(record);
        }
        if (ORDER_TYPE_INSTORE.equals(order.getType()) && order.getBalance().compareTo(new BigDecimal(0)) != 0) {
            record.setTransType(RECORT_TYANSTYPE_BALANCE_INORDER);
            record.setMoney(order.getBalance());
            recordService.insert(record);
        }
        if (ORDER_TYPE_OUTSTORE.equals(order.getType()) && order.getIncome().compareTo(new BigDecimal(0)) != 0) {
            record.setTransType(RECORT_TYANSTYPE_INCOME_OUTORDER);
            record.setMoney(order.getIncome());
            recordService.insert(record);
        }
        if (ORDER_TYPE_OUTSTORE.equals(order.getType()) && order.getBalance().compareTo(new BigDecimal(0)) != 0) {
            record.setTransType(RECORT_TYANSTYPE_BALANCE_OUTORDER);
            record.setMoney(order.getBalance());
            recordService.insert(record);
        }
        //买家上级数据更新
        if (!"0".equals(buyer.getPid())) {
            //上级返利
            User supUser = new User();
            supUser.setId(buyer.getPid());
            supUser = userService.selectOne(supUser);
            BigDecimal brokerage = order.getOtotal().multiply(new BigDecimal("0.2"));
            brokerage = brokerage.setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal income = supUser.getIncome().add(brokerage);
            supUser.setIncome(income);
            userService.update(supUser);
            //上级交易记录
            Record recordInfo = new Record();
            recordInfo.setUserID(supUser.getId());
            if (ORDER_TYPE_INSTORE.equals(order.getType())) {
                recordInfo.setTransType(RECORT_TYANSTYPE_SUB_INORDER);
            } else {
                recordInfo.setTransType(RECORT_TYANSTYPE_SUB_OUTORDER);
            }
            recordInfo.setTransID(order.getId());
            recordInfo.setMoney(order.getOtotal().multiply(new BigDecimal("0.2")));
            recordService.insert(recordInfo);
        }
        //待付款订单模板消息推送
        Store store = new Store();
        store.setId(order.getStoreID());
        store = storeService.selectOne(store);
        Map<String, String> msgParam = new HashMap<>();
        msgParam.put("first", "您好，您有个订单等待付款！");
        msgParam.put("keyword1", store.getName());
        msgParam.put("keyword2", order.getPtotal().toString());
        msgParam.put("keyword3", order.getCreateTime());
        msgParam.put("remark", "请及时支付！");
        WxMsgUtil.sendUnPayStatusMsg(msgParam, systemManager, buyer.getOpenID(), order);
        return new JSONResult<>(orderID, true);
    }

    /**
     * 打印订单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("printOrder")
    @ResponseBody
    public JSONResult printOrder(String content,String SN,String KEY) {
        PrintUtils printUtils = new PrintUtils(SN,KEY);
        printUtils.print(content);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setSuccess(true);
        return jsonResult;
    }
}
